package cn.juque.lucenecandy.threads;

import cn.hutool.core.thread.ThreadUtil;
import cn.juque.lucenecandy.cache.IndexWriterCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>CommitIndexWriterThreadPool</li>
 * </ul>
 * @date 2023-12-25
 **/
@Slf4j
@Component("indexWriterThreadPool")
public class IndexWriterThreadPool {

    private static final ThreadFactory THREAD_FACTORY = ThreadUtil.newNamedThreadFactory("commit-index-", true);

    private static final ScheduledExecutorService EXECUTOR =
            new ScheduledThreadPoolExecutor(1, THREAD_FACTORY, new ThreadPoolExecutor.DiscardPolicy());

    private static final AtomicBoolean END = new AtomicBoolean(true);

    @Resource
    private IndexWriterCache indexWriterCache;

    public void init() {
        EXECUTOR.scheduleWithFixedDelay(this::commit, 0, 5, TimeUnit.SECONDS);
        log.debug("完成IndexWriter提交线程的初始化");
    }

    private void commit() {
        if (END.compareAndSet(true, false)) {
            return;
        }
        this.indexWriterCache.commit();
        END.set(true);
    }
}
